<?php
class CharactersController extends Zend_Controller_Action
{
	
	
	function init() 
	{
		// Initialize the view
		$this->initView();
		// Store the base url for the current request in the view
		$this->view->baseUrl = $this->_request->getBaseUrl();	
	}
	
	
	function getListAction() 
	{	
		$this->_helper->viewRenderer->setNoRender();
		
		// Empty result
		$result = array();
		
		// Get the query
		$query = $this->_request->getParam('q');
		
		// Fetch all characters as a array
		$charactersTable = new Characters();
		$select = $charactersTable->select()->where("name LIKE ?", $query . "%");
		$characters = $charactersTable->fetchAll($select);
			
		foreach($characters as $character) {
			$result[] = array( "id"    => $character->id,
				               "name"  => $character->name );
		}
		
		echo $this->_helper->jsonResponse($result);
	}
	
	function indexAction()
	{
		

	}
	
	/**
	 * Attempts to pull a char name from the armory
	 * (this is only a test function for the 
	 * ArmoryProfile model at the moment)
	 */
	function lookupAction()
	{
		if ($this->_request->isPost()) {
			
			$profile = new ArmoryProfile();
			$profile->pull($this->_request->getParam('name'));
			
		}
	}
	
	function createAction()
	{
		if (!Zend_Auth::getInstance()->hasIdentity())return;
		$form = new Forms_CreateCharacterForm();
		
		if ($this->_request->isPost()) {
        	$formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
            	                              
                $character = new Characters();
                $classID = $this->_request->getParam('class');
                $data = array(
                	'user_id'	=> Zend_Auth::getInstance()->getIdentity()->id,
					'name' 		=> $this->_request->getParam('character_name'),
					'class_id'	=> $classID,
                	'main'		=> !$this->userHasMainCharacter()
				);
				$characterID = $character->insert($data);

				$classes = new Classes();
				$row = $classes->fetchRow('id='.$classID);				
				$roles = $row->findRolesViaClassesRoles();
										
				$charRoleRankTable = new CharactersRolesRanks();
				foreach ($roles as $role)
				{
					$roleData = array(
					'character_id'	=> $characterID,
					'role_id'		=> $role->role_id, 
					);	
				$charRoleRankTable->insert($roleData);				
				}				
				
                
            } else {
            	$form->populate($formData);
            }
        }
		
		$this->view->form = $form;
	}
	
	//AJAX action
	function getCharactersAction(){
		$this->_helper->viewRenderer->setNoRender();
		
		if (!Zend_Auth::getInstance()->hasIdentity()){
			echo $this->_helper->jsonError("Login required");
			return;
		}
		
		$userId = Zend_Auth::getInstance()->getIdentity()->id;
		if (!$userId){
			echo $this->_helper->jsonError("Login required");
			return;
		}
			
		$charactersTable = new Characters();
		$select = $charactersTable->select()
					->where('user_id = ?', $userId);							
		$characters = $charactersTable->fetchAll($select);		

		if (!$characters){
			echo $this->_helper->jsonError("No characters found");
			return;
		}
		
		$result = array();
		
		foreach ($characters as $char){
			$result[] = array(	'id' 			=> $char->id,
								'name'			=> $char->name,
								'class_name'	=> $char->findParentRow('Classes','Classes')->name,
								'main'			=> $char->main,
								'default_role'	=> $char->default_role,
								'default_note'	=> $char->default_note,
								'roles'			=> $char
											->findParentRow('Classes','Classes')
											->findManyToManyRowset('Roles','ClassesRoles','Classes','Roles')->toArray()
			);
		}
		
		echo $this->_helper->jsonResponse($result);			
	}
	
	// TODO This might be in the wrong place... the Character model might be more appropriate
	private function userHasMainCharacter()
	{
		$characters = new Characters();
		
		$select = $characters->select();
		$select->where('user_id = ?',Zend_Auth::getInstance()->getIdentity()->id)
			->where('main = ?',1);
		
		return $characters->fetchAll($select)->valid();
	}
	
	/**
	 * 
	 * @return unknown_type
	 */
	public function getCharacterListAction()
	{
		// http://techchorus.net/autocomplete-example-zenddojoformelementfiltringselect-and-zenddojodata 
		// http://weierophinney.net/matthew/archives/198-Autocompletion-with-Zend-Framework-and-Dojo.html
		
		// Disable view rendering for this action
		$this->_helper->viewRenderer->setNoRender();
		
		// Fetch all characters as a array
		$charactersTable = new Characters();
		$characters = $charactersTable->fetchAll();
		
		// Create dojo data 
		$data = new Zend_Dojo_Data('id', $characters->toArray(), "name");
		echo $data->toJson();
	}
}